package com.thinksns.sociax.t4.android.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import com.thinksns.sociax.android.R;
import com.thinksns.sociax.api.Api;
import com.thinksns.sociax.t4.adapter.AdapterUserFollowingListNew;
import com.thinksns.sociax.t4.android.Thinksns;
import com.thinksns.sociax.t4.android.data.StaticInApp;
import com.thinksns.sociax.t4.android.user.ActivityUserInfo_2;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.model.ModelSearchUser;
import com.thinksns.sociax.t4.model.ModelUser;
import com.thinksns.sociax.t4.model.ModelWeibo;
import com.thinksns.sociax.t4.unit.UnitSociax;
import com.thinksns.sociax.thinksnsbase.base.BaseListFragment;
import com.thinksns.sociax.thinksnsbase.base.BaseListPresenter;
import com.thinksns.sociax.thinksnsbase.base.IBaseListView;
import com.thinksns.sociax.thinksnsbase.base.ListBaseAdapter;
import com.thinksns.sociax.thinksnsbase.bean.ListData;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.Serializable;
import java.util.List;

/**
 * Created by hedong on 16/2/29.
 * 用户关注、粉丝列表
 */
public class FragmentUserFollowingListNew extends BaseListFragment<ModelSearchUser> {
    public static final int TYPE_FOLLOWING = 1; // 关注列表
    public static final  int TYPE_FOLLOWED = 0; // 粉丝列表
    private int type;
    private int uid;
    public String name = "";
    protected BroadcastReceiver mUpdateFollowRecevier;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        /**搜索无需保存缓存**/
        mPresenter.setSaveCache(false);
        mPresenter.loadInitData(true);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            type = getArguments().getInt("type", 0);  // 获取用户列表 1：关注 0：粉丝列表
            uid = getArguments().getInt("uid", 0);
        }
        if (uid == 0) {
            uid = Thinksns.getMy().getUid();
        }
        name = getName();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        getActivity().unregisterReceiver(mUpdateFollowRecevier);
    }

    @Override
    protected ListBaseAdapter<ModelSearchUser> getListAdapter() {
        return new AdapterUserFollowingListNew(getActivity());
    }

    @Override
    protected void initPresenter() {
        mPresenter = new UserFollowingPresenter(getActivity(), this);
        if (type == 1) {
            // 关注
            mPresenter.setCacheKey("following");
        } else {
            // 粉丝
            mPresenter.setCacheKey("follow");
        }
    }

    @Override
    protected void initReceiver() {
        super.initReceiver();
        mUpdateFollowRecevier = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                // 对某用户关注/取消关注后触发的
                if (action.equals(StaticInApp.NOTIFY_FOLLOW_USER)) {
                    int uid = intent.getIntExtra("uid", 0);
                    int follow = intent.getIntExtra("follow", 0);
                    if (uid > 0) {
                        updateUserFollow(uid, follow);
                    }
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter(StaticInApp.NOTIFY_FOLLOW_USER);
        if (intentFilter != null) {
            getActivity().registerReceiver(mUpdateFollowRecevier, intentFilter);
        }
    }

    @Override
    protected void initListViewAttrs() {
        mListView.setDivider(new ColorDrawable(getResources().getColor(R.color.bg_ios)));
        mListView.setDividerHeight(UnitSociax.dip2px(getActivity(), 0.5f));
    }

    @Override
    public void onLoadDataSuccess(ListData<ModelSearchUser> data) {
        // 设置缺省图文
        if (type == TYPE_FOLLOWING) {
            mEmptyLayout.setNoDataContent(getResources().getString(R.string.empty_user_followed));
        } else {
            mEmptyLayout.setNoDataContent(getResources().getString(R.string.empty_user_following));
        }
        // 搜索用户时无结果改变缺省文字
        if (!TextUtils.isEmpty(name)){
            mEmptyLayout.setNoDataContent(getResources().getString(R.string.search_no_match));
        }
//        mEmptyLayout.setErrorImag(R.drawable.ic_no_yh);

        super.onLoadDataSuccess(data);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ModelSearchUser user = mAdapter.getItem((int) id);
        if (user != null) {
            // 点击列表进入用户主页
            Intent intent = new Intent(getActivity(), ActivityUserInfo_2.class);
            //4.5增加能否进入个人中心的判断
            if (Thinksns.getMy().getUid() != user.getUid() && ModelUser.CAN_NOT_TO_HOME == user.getSpace_privacy()) {
                ToastUtils.showToast(R.string.tip_no_oauth_to_other_home);
            } else {
                intent.putExtra("uid", user.getUid());
                startActivity(intent);
            }


        }
    }

    private class UserFollowingPresenter extends BaseListPresenter<ModelSearchUser> {

        public UserFollowingPresenter(Context context, IBaseListView<ModelSearchUser> baseListView) {
            super(context, baseListView);
        }

        @Override
        public ListData<ModelSearchUser> parseList(String result) {
            ListData<ModelSearchUser> listData = new ListData<ModelSearchUser>();
            try {
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    ModelSearchUser follow;
                    try {
                        follow = new ModelSearchUser(jsonArray.getJSONObject(i));
                        if (follow.getUid() != 0)
                            listData.add(follow);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return listData;
        }

        @Override
        protected ListData<ModelSearchUser> readList(Serializable seri) {
            return (ListData<ModelSearchUser>) seri;
        }

        @Override
        public String getCachePrefix() {
            return "user_list_";
        }

        @Override
        public void loadNetData() {
            if (type == TYPE_FOLLOWING) {
                // 获取关注的人列表
                new Api.Users().getUserFollowingList(uid, name, getMaxId(), mHandler);
            } else {
                new Api.Users().getUserFollowList(uid, name, getMaxId(), mHandler);
            }
        }
    }

    /**
     * 刷新关注、取消关注用户的状态
     *
     * @param following
     */
    private void updateUserFollow(int uid, final int following) {
        for (int i = 0; i < mAdapter.getDataSize(); i++) {
            if (mAdapter.getItem(i).getUid() == uid) {
                if (type == TYPE_FOLLOWED) { // 1：关注 0：粉丝列表
                    mAdapter.getItem(i).setFollowing(String.valueOf(following));
                } else if (type == TYPE_FOLLOWING && following == 0) {
                    /*关注列表 following = 0 时取消关注，移除列表，updated 3/7/2017 by leiyan*/
                    mAdapter.removeItem(mAdapter.getItem(i));
                }
                break;
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    @Subscribe
    public void updateRemark(ModelUser user){
        if (mAdapter != null && mAdapter.getDataSize() >0){
            ListData<ModelSearchUser> userList = mAdapter.getData();
            int size = userList.size();
            ModelSearchUser friend;
            for (int i = 0; i < size; i++){
                friend = (ModelSearchUser) userList.get(i);
                if (friend.getUid() == user.getUid()){
                    friend.setRemark(user.getBeizhu());
                    mAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }

    }
}
